package com.kaifamiao.lifecycle;

import com.kaifamiao.util.JdbcHelper;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

public class PassiveServlet implements Servlet {

    private static Class<?> clazz = PassiveServlet.class ;
    private static String className = clazz.getName() ;
    private static Logger logger = Logger.getLogger( className );

    // 使用类初始化块来验证类的加载过程
    static {
        logger.info( "类加载时执行对" + className + "类初始化" );
    }

    private ServletConfig config ;

    private JdbcHelper helper ;

    public PassiveServlet(){
        logger.info( "创建" + className + "类实例" );
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        logger.info( "初始化servlet实例: 接受由容器传递的数据并完成初始化操作" );
        this.config = config ; // 比如将容器传递的数据保存起来
        this.helper = JdbcHelper.getInstance(); // 比如打开数据库连接
    }

    @Override
    public void service(ServletRequest req , ServletResponse resp )
            throws ServletException, IOException {
        logger.info( "提供服务: 接受客户端请求并做出回应" );

        req.setCharacterEncoding( "UTF-8" );
        resp.setCharacterEncoding( "UTF-8" );

        resp.setContentType( "text/html" );

        PrintWriter out = resp.getWriter();

        out.println( "<div style=\"border:1px solie blue;\">" );
        out.println( this.getServletInfo() );
        out.println( "</div>" );

        // PrintWriter 不必关闭，当响应结束时会自动关闭这个流
    }

    @Override
    public void destroy() {
        logger.info( "销毁servlet实例: 释放当前servlet实例所占用的资源" );
        helper.release(); // 比如释放数据库连接
    }

    @Override
    public String getServletInfo() {
        // 获取 <servlet-name> 元素内容 或 @WebServlet注解的 name 属性值
        String servletName = config.getServletName() ;
        return servletName + " : " + className ;
    }

    @Override
    public ServletConfig getServletConfig() {
        return config ;
    }

}
